﻿/**
 * Copyright (C) 2011 original author and authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NGuice.Inject.Matcher;
using NGuice.Inject.Internal.Util;

namespace NGuice.Inject.Spi
{
    //Complete!
    /// <summary>
    /// 用于匹配目标类型的类型转换器注册表。实例在一个module中显式的使用
    /// <code>Binder.ConvertToThypes(IMatcher,TypeConverter)</code>
    /// 语法创建:<code>ConvertToTypes(Matchers.Only(typeof(DateTime)), new DateTimeConverter());</code>
    /// </summary>
    public sealed class TypeConverterBinding : IElement
    {
        private readonly object source;

        private readonly IMatcher typeMatcher;//泛型参数必须为Type的超类

        private readonly ITypeConverter typeConverter;

        /** @since 3.0 */
        public TypeConverterBinding(object source, IMatcher typeMatcher, ITypeConverter typeConverter)
        {
            this.source = Preconditions.CheckNotNull(source, "source");
            this.typeMatcher = Preconditions.CheckNotNull(typeMatcher, "typeMatcher");
            this.typeConverter = Preconditions.CheckNotNull(typeConverter, "typeConverter");
            Preconditions.CheckSuperGenericParameter<Type>(typeMatcher);
        }

        public object Source
        {
            get { return source; }
        }

        public IMatcher TypeMatcher
        {
            get { return typeMatcher; }
        }

        public ITypeConverter TypeConverter
        {
            get { return typeConverter; }
        }

        public T AcceptVisitor<T>(IElementVisitor<T> visitor)
        {
            return visitor.Visit(this);
        }

        public void ApplyTo(IBinder binder)
        {
            binder.WithSource(Source).ConvertToTypes(typeMatcher, typeConverter);
        }

        public override string ToString()
        {
            return typeConverter + " which matches " + typeMatcher
                + " (bound at " + source + ")";
        }

    }
}
